import React from 'react'
import CustomBreadcrumb from '../../components/CustomBreadcrumb/index'
import {
    Table,
    Button,
    Input,
    Modal,
    Tabs,
    Form,
    Select,
    Col,
    Row,
    Tree,
    Checkbox,
    message,
    Popconfirm,
    DatePicker,
    BackTop
} from 'antd';
import {groupPlucks,addRoles,getRoles,getRoleDetails,getRolesPermission,delRole,editRoles} from "../../api/role";
import {getPermissions} from "../../api/permissions";
import { getAllMenus,bindRoleMenu,getRoleMenus} from "../../api/menu";
import './index.css';


const {Search} = Input;
const {TabPane} = Tabs;
const {Option} = Select;
const {TreeNode} = Tree;
const CheckboxGroup = Checkbox.Group;
const defaultCheckedList = [];
const { RangePicker } = DatePicker;
const InputGroup = Input.Group;


function callback(key) {
    console.log(key);
}

class Role extends React.Component {
    state = {
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        modal2Visible: false,
        modalRoles: false,
        autoExpandParent: true,
        selectedKeys: [],
        data: [],
        groupPlucks: [],
        plainOptions: [],
        checkedList: defaultCheckedList,
        indeterminate: false,
        checkAll: false,
        allPer:[],
        roleList:[],
        page:1,
        size:100,
        title: '',
        id:'',
        group_id:'',
        role_name:'',
        permissionData:[],
        expandedKeys: [],
        checkedKeys: [],
        treeData:[]

    };
    edit =(id)=>{
        //获取详情
        this._getRoleDetails(id)
        // 获取组
        this._groupPlucks()
        // 获取权限
        this._getPermissions()
        // 获取角色对应权限
        this._getRolesPermission(id)
        this.setState({
            modal2Visible: true,
            title: '修改管理员',
            id,
            form: {}
        });
    }
    /**
     * 获取角色对应的权限
     */
    _getRolesPermission(id) {
        const ids = {
            role_ids: [id]
        }
        getRolesPermission(ids).then((res) => {
            if (res.data && res.data.length > 0) {
                const permissionData = res.data
                this.setState({
                    checkedList:permissionData,
                    permissionData
                })
            } else {
                this.setState({
                    checkedList:[],
                    checkAll: false
                })
            }
        })
    }
    /**
     * 根据id获取角色详情
     */
    _getRoleDetails(id) {
        getRoleDetails(id).then((res)=> {
            if (res.data) {
                this.setState({
                    group_id:res.data.group_id.toString(),
                    role_name:res.data.name,
                    id:res.data.id
                })
                this.props.form.setFieldsValue({
                    group_id:res.data.group_id.toString(),
                    role_name:res.data.name,
                })
            }
        })
    }
    /**
     * 权限更改
     * @param checkedList
     */
    onChangePer = checkedList => {
        this.setState({
            checkedList,
            indeterminate: !!checkedList.length && checkedList.length < this.state.plainOptions.length,
            checkAll: checkedList.length === this.state.plainOptions.length,
        });
    };
    /**
     * 权限选择所有
     * @param checkedList
     */
    onCheckAllChange = e => {
        this.setState({
            checkedList: e.target.checked ? this.state.plainOptions : [],
            indeterminate: false,
            checkAll: e.target.checked
        });
    };
    start = () => {
        this.setState({loading: true});
        // ajax request after empty completing
        setTimeout(() => {
            this.setState({
                selectedRowKeys: [],
                loading: false,
            });
        }, 1000);
    };
    onSelectChange = selectedRowKeys => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({selectedRowKeys});
    };
    componentDidMount() {
        this._getRoles()
    }
    /**
     * 获取角色列表
     */
    _getRoles() {
        const page = this.state.page
        const size = this.state.size
        getRoles(page,size).then((res) => {
            if(res.data && res.data.data.length > 0) {
                this.setState({
                    roleList: res.data.data
                })
            }
        })
    }
    /**
     * 获取组列表
     * @param e
     */
    _groupPlucks() {
        groupPlucks().then((res) => {
            if (res.code < 400) {
                const list = res.data
                const listData = []
                for (let index in list) {
                    let val = {
                        id: index,
                        val: list[index]
                    }
                    listData.push(val)
                }
                this.setState({
                    groupPlucks: listData
                })
            }
        })
    }
    /**
     * 获取所有权限
     * @param e
     */
    _getPermissions() {
        getPermissions().then((res) => {
            const pers = res.data
            if (pers.length > 0) {
                const list = pers.map((item) => {
                    return item.display_name
                })
                this.setState({
                    plainOptions: list,
                    allPer:pers
                })
            }
        })
    }
    handleSelectChange = value => {
        this.props.form.setFieldsValue({
            group_id: value
        });
        this.setState({
            group_id: value
        })
    };
    setModal2Visible(modal2Visible) {
        this.setState({modal2Visible});
    }
    /**
     * 调用添加
     * @returns {*}
     */
    add = () => {
        this.setState({modal2Visible: true,title:'添加角色'});
        // 获取组
        this._groupPlucks()
        // 获取权限
        this._getPermissions()
        this.setState({
            title: '添加角色',
            id:'',
            group_id:'',
            role_name:'',
            checkedList: [],
            indeterminate: false,
            checkAll: false,
            treeData:[]
        });
    }
    /**
     * 添加数据
     * @returns {*}
     */
    handleSubmitthis = () => {
        this.props.form.validateFields((err, values) => {
                if (err === null) {
                    const checkedList = this.state.checkedList
                    if (checkedList.length > 0) {
                        // 获取修改之前的权限
                        const oldPermission = this.state.permissionData
                        // 新添加数据
                        const newPermission = []
                        for(let index in checkedList){
                            if(!oldPermission.includes(checkedList[index])) {
                                newPermission.push(checkedList[index])
                            }
                        }
                        // 删除数据
                        const delPermission = []
                        for(let index in oldPermission){
                            if(!checkedList.includes(oldPermission[index])) {
                                delPermission.push(oldPermission[index])
                            }
                        }
                        const allPerList = this.state.allPer
                        const addPermission_ids = []
                        const delPermission_ids = []
                        for(let index in allPerList) {
                           let add = newPermission.includes(allPerList[index].display_name)
                            if(add) {
                                addPermission_ids.push(allPerList[index].id)
                            }
                            let del = delPermission.includes(allPerList[index].display_name)
                            if(del) {
                                delPermission_ids.push(allPerList[index].id)
                            }
                        }
                        const froms = Object.assign({},values,{
                            add_permissions:addPermission_ids
                        },{delete_permissions:delPermission_ids})
                        const id = this.state.id
                        if(id) {
                            froms.id = id
                            this._editRole(froms)
                        } else {
                            this._addRole(froms)
                        }
                        this.setState({modal2Visible: false});
                    } else {
                        message.warning('请选择角色对应的权限')
                    }
                }

            }
        )
    }
    /**
     * 添加角色
     * @returns {*}
     */
    _addRole(data) {
        addRoles(data).then((res) => {
            if(res.code < 400) {
                this._getRoles()
                message.success('添加数据成功！')
            }
        })
    }
    /**
     * 修改角色
     * @returns {*}
     */
    _editRole(data) {
        editRoles(data).then((res) => {
            if(res.code < 400) {
                this._getRoles()
                message.success('修改数据成功！')
            }
        })
    }
    /**
     * 删除角色
     * @returns {*}
     */
    delConfirm = (id) => {
        delRole(id).then((res) => {
                if (res.code < 400) {
                    this._getRoles()
                    message.success('删除成功！');
                } else {
                    message.success('删除失败！');
                }
            }
        )
    }
    /**
     *input值发生改变
     * @returns {*}
     */
    onChange = (e) => {
        const val = e.target.value
        this.setState({
            role_name:val,
        })
    }
    /**
     * 显示绑定角色
     * @returns {*}
     */
    async roleMenu (id){
        await this._getAllMenus()
        await this._getRoleMenus(id)
        this.setState({
            modalRoles: true,
            id
        })
    }
    /**
     * 获取菜单层级
     * @private
     */
    _getAllMenus = () =>{
        getAllMenus().then((res) => {
            if (res.code < 400) {
                const treeData = res.data
                this.setState({
                    treeData
                })
            }
        })
    }
    onExpand = expandedKeys => {
        console.log('onExpand', expandedKeys);
        // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    };
    /**
     * 添加角色菜单
     * @param checkedKeys
     */
    handleSubmitRoles = () => {
        const checkedKeys = this.state.checkedKeys
        const treeDatas = this.state.treeData
        if(checkedKeys.length >0) {
           const menu_ids  = this._getCheckedIds(checkedKeys,treeDatas)
           const role_id = this.state.id
            var data = {
                menu_ids,
                role_id
            }
            this._bindRoleMenu(data)
        }
    }
    /**
     * 添加角色菜单
     */
    _bindRoleMenu(data){
        bindRoleMenu(data).then((res) => {
            if(res.code <400) {
                message.success('绑定成功!')
                this.setState({
                    modalRoles: false,
                    id:''
                })
            }
        })
    }
    /**
     * 获取被选中的id
     * @param checkedKeys
     */
    _getCheckedIds = (checkedKeys, treeDatas) => {
        const ids = []
        if(treeDatas.length > 0) {
            treeDatas.map(item => {
                if (item.subs) {
                    item.subs.map(item => {
                        if(checkedKeys.includes(item.title)) {
                            ids.push(item.id)
                        }
                        this._getCheckedIds(checkedKeys,item)
                    })
                }
                if(checkedKeys.includes(item.title)) {
                    ids.push(item.id)
                }
            });
        }
        return ids
    }
    /**
     * 获取角色菜单
     * @param checkedKeys
     */
    _getRoleMenus(id) {
        getRoleMenus(id).then((res) => {
            if(res.data) {
                this.setState({
                    checkedKeys:res.data
                })
            }
        })
    }
    onCheck = checkedKeys => {
        this.setState({ checkedKeys });
    };
    onSelect = (selectedKeys, info) => {
        this.setState({ selectedKeys });
    };
    renderTreeNodes = data =>
        data.map(item => {
            if (item.subs) {
                return (
                    <TreeNode title={item.title} key={item.title} dataRef={item}>
                        {this.renderTreeNodes(item.subs)}
                    </TreeNode>
                );
            }
            return <TreeNode  key={item.title} {...item} />;
        });
    render() {
        const columns = [
            {
                title: '序号',
                width: 100,
                align: 'center',
                render: (text, record, index)=>{
                    return (index+1)
                }
            },
            {
                title: '角色名称',
                dataIndex: 'name',
                width: 200,
                align: 'center'
            },
            {
                title: '所属部门',
                width: 200,
                align: 'center',
                render: (text, record) => (
                    <span>{record.group.name}</span>
                )
            },
            {
                title: '创建时间',
                dataIndex: 'created_at',
                width: 200,
                align: 'center'
            },
            {
                title: '操作',
                dataIndex: 'address',
                width: 200,
                align: 'center',
                render: (text, record) => (
                    <span>
                         <Button type="primary" style={{marginRight: 10}} onClick={() => {
                             this.roleMenu(record.id)
                         }}>绑定菜单</Button>
                        <Button style={{marginRight: 10}} onClick={() => {
                            this.edit(record.id)
                        }}>修改</Button>
                        <Popconfirm
                            title="你确认要删除吗?"
                            onConfirm={() => {
                                this.delConfirm(record.id)
                            }}
                            okText="确定"
                            cancelText="取消"
                        >
                        <Button type="danger">删除</Button>
                        </Popconfirm>
                    </span>
                ),
            }
        ];
        const {loading, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <CustomBreadcrumb arr={['角色列表']}/>
                <div style={{marginBottom: 16}}>
                    <InputGroup compact style={{ borderBottom: '16px' }}>
                      <Button type="primary" onClick={this.start} disabled={!hasSelected} loading={loading}>
                          删除
                      </Button>
                      <Input placeholder="请输入角色名称"  style={{ width: 120, borderRight: '1px solid rgb(217,217,217)', borderTopRightRadius: '4px', borderBottomRightRadius: '4px' }} />
                      <span className="changeDate">请输入日期:</span>
                      <RangePicker />
                      <Select defaultValue="总裁" style={{ width: 120 }}>
                        <Option value="总裁">总裁</Option>
                        <Option value="副总裁">副总裁</Option>
                        <Option value="CEO">CEO</Option>
                        <Option value="CFO">CFO</Option>
                      </Select>
                      <Button type="primary" shape="circle" icon="search" />
                    </InputGroup>
                </div>
                <Modal
                    title="添加角色"
                    centered
                    width={1000}
                    visible={this.state.modal2Visible}
                    onOk={() => this.handleSubmitthis()}
                    onCancel={() => this.setModal2Visible(false)}
                >
                    <Tabs defaultActiveKey="1" onChange={callback}>
                        <TabPane tab="角色信息" key="1">
                            <Form>
                                <Form.Item label="选择组">
                                    {getFieldDecorator('group_id', {
                                        rules: [{required: true, message: '请选择组!'}],
                                    })(
                                        <Row span={8}>
                                            <Col span={8}>
                                                <Select
                                                    placeholder="选择组"
                                                    value={this.state.group_id}
                                                    onChange={this.handleSelectChange}
                                                >
                                                    {
                                                        this.state.groupPlucks.map((item) => {
                                                            return (<Option value={item.id} key={item.id}>{item.val}</Option>)
                                                        })
                                                    }

                                                </Select>
                                            </Col>
                                        </Row>
                                    )}
                                </Form.Item>
                                <Form.Item label="角色名称">
                                    {getFieldDecorator('role_name', {
                                        rules: [{required: true, message: '请输入角色名称!'}],
                                    })(
                                        <Row span={8}>
                                            <Col span={8}> <Input value={this.state.role_name} onChange={this.onChange} placeholder="请输入角色名称"/></Col>
                                        </Row>
                                    )}
                                </Form.Item>
                            </Form>
                        </TabPane>
                        <TabPane tab="访问权限" key="2">
                            <div>
                                <div style={{borderBottom: '1px solid #E9E9E9'}}>
                                    <Checkbox
                                        indeterminate={this.state.indeterminate}
                                        onChange={this.onCheckAllChange}
                                        checked={this.state.checkAll}
                                    >
                                        全选
                                    </Checkbox>
                                </div>
                                <br/>
                                <CheckboxGroup
                                    options={this.state.plainOptions}
                                    value={this.state.checkedList}
                                    onChange={this.onChangePer}
                                />
                            </div>
                        </TabPane>
                    </Tabs>,
                </Modal>
                <Modal
                    title="角色绑定菜单"
                    centered
                    width={1000}
                    visible={this.state.modalRoles}
                    onOk={() => this.handleSubmitRoles()}
                    onCancel={() => this.setState({modalRoles:false})}
                >
                    <Tree
                        checkable
                        onExpand={this.onExpand}
                        expandedKeys={this.state.expandedKeys}
                        autoExpandParent={this.state.autoExpandParent}
                        onCheck={this.onCheck}
                        checkedKeys={this.state.checkedKeys}
                        onSelect={this.onSelect}
                        selectedKeys={this.state.selectedKeys}
                    >
                        {this.renderTreeNodes(this.state.treeData)}
                    </Tree>
                </Modal>
                {/* <BackTop visibilityHeight={100} style={{right: 16, bottom: 62}}/> */}
                <Table rowSelection={rowSelection} rowKey='id' columns={columns} dataSource={this.state.roleList}/>
            </div>
        );
    }
}

const RoleFrom = Form.create()(Role);
export default RoleFrom
